﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using ScFramework.Core;

public class EntityData
{
    /// <summary>
    /// 左16位实体预设id,右16位实体id
    /// </summary>
    public UInt32 EntityIdentity;
    public List<ComponentData> ComponentDatas = new List<ComponentData>();
}

public static class EntityDataExtensions
{

    public static string GetEntityName(this EntityData e)
    {
        return EntityUtilities.GetEntityName(e.EntityIdentity.left());
    }
    /// <summary>
    /// 返回一个该类型的数据,若有多个返回第一个
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="id"></param>
    /// <returns></returns>
    public static ComponentData GetComponentData(this EntityData e,Type t) 
    {
        if( e is null)
        {
            Debug.LogError($"{e} is null");
        }
        Debug.Assert(typeof(SComponent).IsAssignableFrom(t));
        var ans = e.ComponentDatas.Find(s => t.IsAssignableFrom(s.ComponentType));
        if (ans == null)
        {
            return null;
            // throw new Exception($"{e}: {typeof(T)} 组件未找到");
        }
        return ans;
    }
    /// <summary>
    /// 返回一个该类型的数据,若有多个返回第一个
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="id"></param>
    /// <returns></returns>
    public static ComponentData GetComponentData<T>(this EntityData e) where T : SComponent
    {
       
        return e.GetComponentData(typeof(T));
    }

    public static ComponentData GetComponentData(this EntityData e,UInt16 id)
    {
        return e.ComponentDatas[id];
        /*if (_componentDataDic.ContainsKey(id))
        {
            return _componentDataDic[id];
        }
        else
        {
            throw new Exception($"{this}: {id} 组件未找到");
        }*/
    }

    /// <summary>
    /// 返回所有该类型的数据
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <returns></returns>
    public static List<ComponentData> GetComponentDatas(this EntityData e,Type t)
    {
        return e.ComponentDatas.FindAll(s => t.IsAssignableFrom(s.ComponentType));
    }
    /// <summary>
    /// 返回所有该类型的数据
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <returns></returns>
    public static List<ComponentData> GetComponentDatas<T>(this EntityData e) where T : SComponent
    {
        return e.ComponentDatas.FindAll(s =>  typeof(T).IsAssignableFrom(s.ComponentType));
    }

}